package com.zyzd.baseokhttp.net;

import android.os.AsyncTask;

import com.zyzd.commontools.image.ImageUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by LZY on 2017/6/26.
 */

public class OkHttpUtil {

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public static final String FILENAME = "uploadimg";

    public static final String UPLOAD_URL_IMAGE_SINGLE = "";
    public static final String UPLOAD_URL_IMAGE_MULT = "";


    private final static OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .connectionPool(new ConnectionPool(20, 5, TimeUnit.MINUTES))
            .readTimeout(20, TimeUnit.SECONDS)
            .connectTimeout(20, TimeUnit.SECONDS).build();


    /**
     * 上传单张图片
     *
     * @param file
     * @param callback
     * @param tag
     */
    public static void uploadImage(File file, Callback callback, Object tag) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .addFormDataPart(FILENAME, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));

        enqueueByPost(UPLOAD_URL_IMAGE_SINGLE, builder.build(), callback, tag);
    }

    /**
     * 上传单张图片，上传前会进行压缩
     *
     * @param filePath
     * @param callback
     * @param tag
     */
    public static void uploadImage(final String filePath, final Callback callback, final Object tag) {
        new AsyncTask<Object, Void, File>() {
            @Override
            protected void onPreExecute() {
            }

            @Override
            protected File doInBackground(Object... params) {
                return ImageUtil.imageZoom(filePath, 100);
            }

            @Override
            protected void onPostExecute(File file) {
                uploadImage(file, callback, tag);
            }
        }.execute();
    }


    /**
     * 上传多张图片
     *
     * @param files
     * @param callback
     * @param tag
     */
    public static void uploadImages(List<File> files, Callback callback, Object tag) {

        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (File file : files) {
            builder.addFormDataPart(FILENAME, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
        }

        enqueueByPost(UPLOAD_URL_IMAGE_MULT, builder.build(), callback, tag);
    }

    /**
     * 上传多张图片（上传前进行压缩）
     *
     * @param files
     * @param callback
     * @param tag
     */
    public static void uploadZoomImages(final List<File> files, final Callback callback, final Object tag) {
        new AsyncTask<Object, Void, List<File>>() {
            @Override
            protected void onPreExecute() {
            }

            @Override
            protected List<File> doInBackground(Object... params) {
                ArrayList<File> zoomFiles = new ArrayList<>();
                if (files != null && files.size() > 0) {
                    for (File file : files) {
                        File zoomFile = ImageUtil.imageZoom(file.getAbsolutePath(), 100);
                        if (zoomFile != null) {
                            zoomFiles.add(zoomFile);
                        }
                    }
                }
                return files;
            }

            @Override
            protected void onPostExecute(List<File> zoomFiles) {
                uploadImages(zoomFiles, callback, tag);
            }
        }.execute();
    }


    /**
     * post 表单提交
     *
     * @param url
     * @param params
     * @param callback
     * @param tag
     */
    public static void formPost(String url, Map<String, String> params, Callback callback, Object tag) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        enqueueByPost(url, builder.build(), callback, tag);
    }

    /**
     * post 请求（同步）
     *
     * @param url
     * @param requestBody
     * @param callback
     * @param tag
     */
    public static void enqueueByPost(String url, RequestBody requestBody, Callback callback, Object tag) {

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .tag(tag)
                .build();

        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * get请求(异步)
     *
     * @param url
     * @param callback
     */
    public static void enqueueByGet(String url, Callback callback, Object tag) {
        Request request = new Request.Builder()
                .url(url)
                .tag(tag)
                .build();

        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * get请求（同步）
     *
     * @param url
     * @param tag
     * @return
     */
    public static Response executeByGet(String url, Object tag) {
        Request request = new Request.Builder()
                .url(url)
                .tag(tag)
                .build();

        try {
            return mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求（同步）
     *
     * @param url
     * @param requestBody
     * @param tag
     * @return
     */
    public static Response executeByGet(String url, RequestBody requestBody, Object tag) {

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .tag(tag)
                .build();

        try {
            return mOkHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
